package prassein.rsm.web;

import java.util.Map;

import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.springframework.beans.factory.annotation.Autowired;

import prassein.rsm.common.utils.Constants;
import prassein.rsm.dao.base.PermLevelDao;
import prassein.rsm.entity.base.User;
import prassein.rsm.service.base.AuditManager;
import prassein.rsm.service.base.UserManager;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

@Results({@Result(name = "success",location="resumeListUndue.jsp")})
public class LoginAction extends ActionSupport {

	private static final long serialVersionUID = 1L;

	@Autowired
	private UserManager userManager;
	
	@Autowired
	private AuditManager auditManager;
	
	@Autowired
	private PermLevelDao permLevelDao;
	
	private User user;

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	@Override 
	public String execute() throws Exception {
		if (user != null && !user.getUserName().equals("")) {
			User userTemp = userManager.getUser(user.getUserName());
			if (user.getUserName().equals(userTemp.getUserName()) && user.getPassword().equals(userTemp.getPassword())) {
				Map<String, Object> session = ActionContext.getContext().getSession();
				session.put(Constants.LOGIN_STATE, "true");
				session.put(Constants.USERNAME, user.getUserName());
				session.put(Constants.PERM_LEVEL, permLevelDao.get(userTemp.getPermLevel()).getResumePerm());
				
				String userName = session.get(Constants.USERNAME).toString();
				auditManager.save(userName, "", "登录");
				
				return SUCCESS;
			} else {
				return INPUT;
			}
		} else {
			Map<String, Object> session = ActionContext.getContext().getSession();
			if (session.get(Constants.USERNAME) != null) {
				auditManager.save(session.get(Constants.USERNAME).toString(), "", "退出");
			}
			return INPUT;
		}
	}

	public UserManager getUserManager() {
		return userManager;
	}

	public void setUserManager(UserManager userManager) {
		this.userManager = userManager;
	}

	public PermLevelDao getPermLevelDao() {
		return permLevelDao;
	}

	public void setPermLevelDao(PermLevelDao permLevelDao) {
		this.permLevelDao = permLevelDao;
	}

	public AuditManager getAuditManager() {
		return auditManager;
	}

	public void setAuditManager(AuditManager auditManager) {
		this.auditManager = auditManager;
	}

}
